package com.example.nio.config;

import cn.hutool.json.JSONUtil;
import com.example.nio.commons.Message;
import com.example.nio.commons.User;
import com.example.nio.util.BridgeUtil;
import com.example.nio.util.WxUtils;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName DirectReceiver 消息接收监听
 * @Description TODO
 * @Author XavierLee
 * @Date 2020/2/26 9:54
 * @Version 1.0
 **/

@Component
@Slf4j
@RabbitListener(queues = "${spring.rabbitmq.directqueue}")
public class DirectReceiver {
    @Autowired
    private WxUtils wxUtils;
    @RabbitHandler
    public void process(String result) {
        log.info("DirectReceiver消费者收到消息: " + result);
        try {
            Message message = JSONUtil.toBean(result, Message.class);
            if (message.getMessageSource() == 2){
                wxUtils.sendToWx(message);
            } else{
                String ipAddress = message.getToUser();
                Channel channel = User.getChannelByIp(ipAddress);
                BridgeUtil.toClient(message,channel);
            }
        } catch (Exception e){
            log.info("客户端rabbitmq消息解析失败");
        }
    }
}
